//
//  ThreeInputView.m
//  ROSE
//
//  Created by 艾阳 on 2018/6/4.
//  Copyright © 2018年 HeNanZhongDunYunAn. All rights reserved.
//

#import "ThreeInputView.h"
#import "UIWindow+CurrentViewController.h"
#import "ScanViewController.h"

@interface ThreeInputView()<UITextFieldDelegate>

@property (nonatomic,strong) UILabel *titleLabel1;
@property (nonatomic,strong) UILabel *titleLabel2;
@property (nonatomic,strong) UILabel *titleLabel3;
@property (nonatomic,strong) UIButton *countDownButton;
@property (nonatomic,strong) UIButton *scanButton;
@end


@implementation ThreeInputView{
    UITextField *_scanTextField;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        if (!_textField1) {
            _textField1 = [[UITextField alloc]init];
            _textField1.delegate  = self;
            UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0,40-2, size_width-40, 1)];
            line.backgroundColor=[UIColor lightGrayColor];
            line.alpha = 0.5;
            [_textField1 addSubview:line];
            
            
            [self addSubview:_textField1];
        }
        if(!_textField2){
            _textField2 = [[UITextField alloc]init];
            _textField2.delegate  = self;
            UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0,40-2, size_width-40, 1)];
            line.backgroundColor=[UIColor lightGrayColor];
            line.alpha = 0.5;
            [_textField2 addSubview:line];
            [self addSubview:_textField2];
        }
        if (!_textField3) {
            _textField3 = [[UITextField alloc]init];
            _textField3.delegate  = self;
            UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0,40-2, size_width-40, 1)];
            line.backgroundColor=[UIColor lightGrayColor];
            line.alpha = 0.5;
            [_textField3 addSubview:line];
            [self addSubview:_textField3];
        }
        
        if (!_titleLabel1) {
            _titleLabel1 = [[UILabel alloc]init];
            _titleLabel1.textColor = [UIColor blackColor];
            _titleLabel1.textColor = [UIColor colorWithRed:70/255.0 green:51/255.0 blue:51/255.0 alpha:1];
            _titleLabel1.font = [UIFont systemFontOfSize:14];
            [self addSubview:_titleLabel1];
        }
        if (!_titleLabel2) {
            _titleLabel2 = [[UILabel alloc]init];
            _titleLabel2.textColor = [UIColor blackColor];
            _titleLabel2.textColor = [UIColor colorWithRed:70/255.0 green:51/255.0 blue:51/255.0 alpha:1];
            _titleLabel2.font = [UIFont systemFontOfSize:14];
            [self addSubview:_titleLabel2];
        }
        if (!_titleLabel3) {
            _titleLabel3 = [[UILabel alloc]init];
            _titleLabel3.textColor = [UIColor blackColor];
            _titleLabel3.textColor = [UIColor colorWithRed:70/255.0 green:51/255.0 blue:51/255.0 alpha:1];
            _titleLabel3.font = [UIFont systemFontOfSize:14];
            [self addSubview:_titleLabel3];
        }
        
        [self makeLayout];
    }
    return self;
}


- (void)makeLayout{
    [self.titleLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(16);
    }];
    [self.textField1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(self.titleLabel1.mas_bottom).with.offset(10);
        make.height.mas_equalTo(40);
    }];
    [self.titleLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(self.textField1.mas_bottom).with.offset(30);
        make.height.mas_equalTo(16);
    }];
    [self.textField2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(self.titleLabel2.mas_bottom).with.offset(10);
        make.height.mas_equalTo(40);
    }];
    [self.titleLabel3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(self.textField2.mas_bottom).with.offset(30);
        make.height.mas_equalTo(16);
    }];
    [self.textField3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(self.titleLabel3.mas_bottom).with.offset(10);
        make.height.mas_equalTo(40);
    }];
    
    
}

- (void)setTitle:(NSArray *)titleArray PlaceHolder:(NSArray *)placeHolderArray{
    self.titleLabel1.text = titleArray[0];
    self.titleLabel2.text = titleArray[1];
    self.titleLabel3.text = titleArray[2];
    
    self.textField1.placeholder = placeHolderArray[0];
    [self.textField1 setValue:[UIFont systemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
    self.textField2.placeholder = placeHolderArray[1];
    [self.textField2 setValue:[UIFont systemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
    self.textField3.placeholder = placeHolderArray[2];
    [self.textField3 setValue:[UIFont systemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
    
}
#pragma mark - 验证码

/**
 设置验证码按钮
 */
- (void)setCountDownInTextfield:(UITextField *)textfield{
    self.countDownButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 90, 20)];
    self.countDownButton.backgroundColor =[UIColor colorWithRed:255/255.0 green:204/255.0 blue:255/255.0 alpha:1];
    [self.countDownButton setTitleColor:[UIColor themeColor] forState:UIControlStateNormal];
    [self.countDownButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.countDownButton.titleLabel.font = [UIFont systemFontOfSize:13];
    self.countDownButton.layer.masksToBounds  = YES;
    self.countDownButton.layer.borderWidth = 1.0f;
    self.countDownButton.layer.borderColor = [UIColor themeColor].CGColor;
    self.countDownButton.layer.cornerRadius = 10.0f;
    textfield.rightView = self.countDownButton;
    textfield.rightViewMode = UITextFieldViewModeAlways;
    [self.countDownButton addTarget:self action:@selector(getVerifyCode) forControlEvents:UIControlEventTouchUpInside];
    
}


/**
 获取验证码
 */
- (void)getVerifyCode{
    [[LMJRequestManager sharedManager] POST:[NSString stringWithFormat:@"%@/usercenter/validatetozh",url_base] parameters:nil completion:^(LMJBaseResponse *response) {
        if (response.error==NULL&&[response.responseObject[@"errorcode"] isEqualToString:@"000000"]) {
            [self changeSureCodeType];
        }
    }];
}

/**
 验证码倒计时
 */
- (void)changeSureCodeType{
    //发送验证码倒计时
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //倒计时完毕0-按钮的样式
                [self.countDownButton setTitle:@"重新发送" forState:UIControlStateNormal];
                self.countDownButton.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //按钮读秒效果
                [self.countDownButton setTitle:[NSString stringWithFormat:@"%.2d", seconds] forState:UIControlStateNormal];
                self.countDownButton.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}
#pragma mark - 扫码

/**
 设置扫码按钮
 */
- (void)setScanButtonInTextfield:(UITextField *)textfield{
    _scanTextField = textfield;
    self.scanButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [self.scanButton setImage:[UIImage imageNamed:@"扫一扫"] forState:UIControlStateNormal];
    textfield.rightView = self.scanButton;
    textfield.rightViewMode = UITextFieldViewModeAlways;
    [self.scanButton addTarget:self action:@selector(goScanView) forControlEvents:UIControlEventTouchUpInside];
}

/**
 开始扫码
 */
- (void)goScanView{
    ScanViewController *scanVc = [[ScanViewController alloc]init];
    [[UIWindow zf_currentViewController].navigationController pushViewController:scanVc animated:YES];
    scanVc.scanSuccess = ^(NSString *scanResult) {
        if (!scanResult.length) {
            return;
        }
       else{
           /** 处理扫码结果*/
           _scanTextField.text = scanResult;
        }
    };
    scanVc.dismissBlock = ^{
    };
}
#pragma mark - Validate

- (BOOL)validateInput{
    if ([self checkPassword:self.textField1.text]&&
        [self checkPassword:self.textField2.text]&&
        [self checkPassword:self.textField3.text]) {
        return YES;
    }else{
        return NO;
    }
}

- (BOOL)checkPassword:(NSString *) password {
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,14}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}




#pragma mark - Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self endEditing:YES];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    [self endEditing:YES];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
